//
//  WLAudioVController.m
//  WanLian
//
//  Created by muzhuang on 2018/10/12.
//  Copyright © 2018年 wanlian. All rights reserved.
//

#import "WLAudioVController.h"
#import "WLVideoAudioCell.h"
#import "WLCloudFileModel.h"
#import "WLCloudMoreView.h"
#import "WLFileRenameAlertView.h"
#import "WLCloudDetailVController.h"
#import "WLDeleteAlertView.h"
#import "UIScrollView+EmptyDataSet.h"

@interface WLAudioVController ()<UITableViewDelegate,UITableViewDataSource,DZNEmptyDataSetSource, DZNEmptyDataSetDelegate>

@property (nonatomic, strong) NSMutableArray *arrAudios;
@property (nonatomic, assign) NSInteger pageAudio;
@property (nonatomic, strong) UITableView *tbAudio;
@property (nonatomic, strong) WLCloudFileModel *selectedModel;

@end

@implementation WLAudioVController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    WLWkSelf
    _arrAudios = [[NSMutableArray alloc] init];
    _pageAudio = 1;
    _tbAudio = [[UITableView alloc] initWithFrame:self.view.bounds style:UITableViewStylePlain];
    _tbAudio.backgroundColor = wlBackColor;
    _tbAudio.delegate = self;
    _tbAudio.dataSource = self;
    _tbAudio.rowHeight = WLScaleX(68);
    _tbAudio.tableFooterView = [UIView new];
    if (@available(iOS 11.0, *)) {
        _tbAudio.estimatedSectionHeaderHeight = 0;
    }
    [self.view addSubview:_tbAudio];
    [_tbAudio mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(weakSelf.view);
    }];
    _tbAudio.mj_header = [WLFreshGifHeader headerWithRefreshingBlock:^{
        weakSelf.tbAudio.mj_footer = nil;
        //        [weakSelf.arrAudios removeAllObjects];
        weakSelf.pageAudio = 1;
        [weakSelf reqCloudPhoto];
    }];
    
    self.tbAudio.emptyDataSetSource = self;
    self.tbAudio.emptyDataSetDelegate = self;
    
    [weakSelf reqCloudPhoto];
}

- (void)addAudioFooterRefresh
{
    WLWkSelf
    _tbAudio.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [weakSelf reqCloudPhoto];
    }];
}

-(void)reqCloudPhoto
{
    WLWkSelf
    NSDictionary *conditions = @{@"fileType":@2};
    NSDictionary *pages = @{@"page":@(_pageAudio),@"num":@10};
    NSDictionary *params = @{@"conditions":conditions,@"page":pages};
    [WLHttpManager WLRequestMethod:RequestTypePost urlStr:@"storage/item/type" withParamsDic:params success:^(NSDictionary *successDict) {
        __strong __typeof(weakSelf) strongSelf = weakSelf;
        [strongSelf.tbAudio.mj_header endRefreshing];
        NSInteger productCount = [successDict[@"count"] integerValue];
        if (strongSelf.pageAudio==1)
        {
            [strongSelf.arrAudios removeAllObjects];
            if (productCount>10)
            {
                [strongSelf addAudioFooterRefresh];
            }
        }
        NSArray *arrPros = [WLCloudFileModel mj_objectArrayWithKeyValuesArray:successDict[@"object"]];
        if (arrPros.count>0) {
            [strongSelf.arrAudios addObjectsFromArray:arrPros];
            if (strongSelf.arrAudios.count >= productCount) {
                [strongSelf.tbAudio.mj_footer endRefreshingWithNoMoreData];
            }
            else
            {
                [strongSelf.tbAudio.mj_footer endRefreshing];
            }
            //            [strongSelf.tbRouter reloadData];
        }
        else
        {
            [strongSelf.tbAudio.mj_footer endRefreshingWithNoMoreData];
        }
        [strongSelf.tbAudio reloadData];
        strongSelf.pageAudio += 1;
    } failure:^(NSString *errorMsg, NSInteger errorTag) {
        [weakSelf showHUDMessage:errorMsg];
        [weakSelf.tbAudio.mj_header endRefreshing];
        [weakSelf.tbAudio.mj_footer endRefreshing];
    } error:^(NSError *error) {
        [weakSelf.tbAudio.mj_header endRefreshing];
        [weakSelf.tbAudio.mj_footer endRefreshing];
    } inView:self.view];
}

#pragma mark - UITableView
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.arrAudios.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *strPhoto = @"photoCell";
    WLVideoAudioCell *cell = [tableView dequeueReusableCellWithIdentifier:strPhoto];
    if (!cell) {
        cell = [[WLVideoAudioCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:strPhoto];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    WLCloudFileModel *fileModel = self.arrAudios[indexPath.row];
    
    [cell.ivHead sd_setImageWithURL:[NSURL URLWithString:fileModel.filePath] placeholderImage:nil];
    cell.labName.text = fileModel.fileName;
    cell.labSize.text = [NSString stringWithFormat:@"%@MB  %@",fileModel.fileSize,[WLCommonTool timeToSlantYMDHMS:fileModel.uploadTime]];
    
    cell.btnMore.tag = indexPath.row;
    [cell.btnMore addTarget:self action:@selector(moreAudioAction:) forControlEvents:UIControlEventTouchUpInside];
    
    return cell;
}

- (void)moreAudioAction:(UIButton *)moreBtn
{
    self.selectedModel = self.arrAudios[moreBtn.tag];
    WLWkSelf
    [WLCloudMoreView showMoreViewTitle:_selectedModel.fileName action:^(NSInteger index) {
        if (index==0) {
//            [weakSelf photoDownload];
        }
        else if (index==1)
        {
            [self deletePhotoAction];
        }
        else if (index==2)
        {
            [self renameAction];
        }
        else if (index==3)
        {
            WLCloudDetailVController *detailController = [[WLCloudDetailVController alloc] init];
//            detailController.fileID = weakSelf.selectedModel.fileId;
            detailController.fileModel = weakSelf.selectedModel;
            [weakSelf.navigationController pushViewController:detailController animated:YES];
        }
    }];
}

- (void)photoDownload
{
    //    UIImageWriteToSavedPhotosAlbum(_ivPhoto.image, self, @selector(image:didFinishSavingWithError:contextInfo:), (__bridge void *)self);
}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
{
    if (!error) {
        [self showHUDMessage:@"已下载到手机相册"];
    }
    //    NSLog(@"image = %@, error = %@, contextInfo = %@", image, error, contextInfo);
}

- (void)deletePhotoAction
{
    WLWkSelf
    WLDeleteAlertView *bindingView = [[WLDeleteAlertView alloc] initWithTitle:_selectedModel.fileName];
    bindingView.okAction = ^{
        [weakSelf deletePhoto];
    };
    [bindingView show];
}

- (void)deletePhoto
{
    WLWkSelf
    NSDictionary *params = @{@"id":@(_selectedModel.fileId)};
    [WLHttpManager WLRequestMethod:RequestTypePost urlStr:@"storage/item/delete" withParamsDic:params success:^(NSDictionary *successDict) {
        [weakSelf showHUDMessage:successDict[@"message"]];
    } failure:^(NSString *errorMsg, NSInteger errorTag) {
        [weakSelf showHUDMessage:errorMsg];
    } error:^(NSError *error) {
        
    } inView:self.view];
}

- (void)renameAction
{
    WLWkSelf
    WLFileRenameAlertView *bindingView = [[WLFileRenameAlertView alloc] initWithTitle:@"重命名文件"];
    bindingView.okAction = ^(NSString * _Nonnull strAddr) {
        [weakSelf renameFile:strAddr];
    };
    [bindingView show];
}

- (void)renameFile:(NSString *)strName
{
    WLWkSelf
    NSDictionary *params = @{@"id":@(_selectedModel.fileId),@"fileName":strName};
    [WLHttpManager WLRequestMethod:RequestTypePost urlStr:@"storage/edit/item" withParamsDic:params success:^(NSDictionary *successDict) {
        weakSelf.selectedModel.fileName = strName;
        [weakSelf showHUDMessage:@"修改成功"];
    } failure:^(NSString *errorMsg, NSInteger errorTag) {
        [weakSelf showHUDMessage:errorMsg];
    } error:^(NSError *error) {
        
    } inView:self.view];
}

#pragma mark - DZNEmpty
- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    return [UIImage imageNamed:@"no_photo"];
}

- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView {
    NSString *title = @"还没有上传音乐哦~";
    NSDictionary *attributes = @{
                                 NSFontAttributeName:[WLCommonTool fontTypePingFangSCRegular:17],
                                 NSForegroundColorAttributeName:wlDarkGrayColor
                                 };
    return [[NSAttributedString alloc] initWithString:title attributes:attributes];
}

- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView
{
    return YES;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
